package com.suncky.example.activity

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.view.View
import android.widget.ImageView
import com.suncky.example.R
import com.suncky.example.databinding.ActivityImagePickerBinding
import com.suncky.frame.AppConfig
import com.suncky.frame.base.BaseViewBindingActivity
import com.suncky.frame.dialog.ImagePickerDialog
import com.suncky.frame.dialog.ImageViewerDialog
import com.suncky.frame.utils.FileUtil
import com.suncky.frame.utils.image.ImageCompressor
import com.suncky.frame.utils.image.ImageCompressor.CompressCallback
import com.suncky.frame.utils.ImagePickHelper
import com.suncky.frame.utils.LogUtils
import com.suncky.frame.utils.glide.GlideUtils
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import java.io.*

class ImagePickerActivity : BaseViewBindingActivity<ActivityImagePickerBinding>() {
    private var imagePickHelper: ImagePickHelper? = null
    private var imagePickDialog: ImagePickerDialog? = null
    private var imageUri: Uri? = null
    private var imagePath: String? = null

    private val imageViewerDialog by lazy {
        object : ImageViewerDialog<String>(context, null) {
            override fun onGetDesc(item: String?, position: Int): String? {
                return item
            }

            override fun onShowImage(item: String?, position: Int, imageView: ImageView?) {
                GlideUtils.load(context,item,imageView,0)
            }
        }.also {
            it.setBackgroundResource(R.color.white)
            it.setDescTextColor(resources.getColor(com.suncky.frame.R.color.color_text_def))
        }
    }

    override fun initView() {
        super.initView()
        defaultTitle.setTitle("ImagePicker")
    }


    override fun initData() {
        super.initData()
        imagePickHelper = ImagePickHelper.with(this)
//            .destinationPath(AppConfig.imagePath)
            .crop(false)
            .cropOption(ImagePickHelper.CropOption.get().scale(true)
                .aspectRatio(1f, 1f).withMaxResultSize(350, 350))
                .callBack { uri, path ->
                    LogUtils.i("uri--->$uri  path--->$path")
                    /*val toPath =
                        AppConfig.imagePath + "compress_" + System.currentTimeMillis() + ".jpg"
                    val success= ImageUtils.compressBitmap(
                        path,
                        toPath,0,500,500
                    )
                    imageUri = FileUtil.getUriForFile(context, toPath)
                    imagePath = toPath
                    if (success) {
                        LogUtils.i("compressed path--->$toPath")
                        GlideUtils.load(context,
                            toPath,
                            binding.imageView,
                            0,
                            true,
                            R.mipmap.ic_launcher_round)
                    }*/

                    compress(listOf(uri))
                }
        imagePickDialog = ImagePickerDialog(context) { t, _, _ ->
            when (t) {
                ImagePickerDialog.PICKER_TYPE_ALBUM -> imagePickHelper?.album()
                ImagePickerDialog.PICKER_TYPE_CAMERA -> imagePickHelper?.camera()
            }
        }
        imagePickDialog?.setTitle("选择图片")
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            binding.imageView.id->{
                imageViewerDialog.imageData = listOf(imagePath)
                imageViewerDialog.show()
            }
            binding.tvSys.id -> imagePickDialog?.show()
            binding.tvThird.id -> {
                Matisse.from(this)
                    ///选择视频和图片
                    // 另：选择图片：MimeType.ofImage() ；选择视频：MimeType.ofVideo() ；
                    //	 自定义选择选择的类型： MimeType.of(MimeType.JPEG,MimeType.AVI...)
                    .choose(MimeType.ofImage())
                    .theme(com.zhihu.matisse.R.style.Matisse_Dracula)
                    //countable属性 true:显示数字,false:显示一个√
                    .countable(false)
                    .capture(true)
                    .maxSelectable(30)
                    .thumbnailScale(0.85f)
                    .imageEngine(GlideEngine())
                    .captureStrategy(CaptureStrategy(true,
                        context.applicationInfo.packageName + ".provider"))
                    .forResult(2)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 2) {
            if (resultCode == RESULT_OK && data != null) {
                val path = Matisse.obtainPathResult(data)
                val uris = Matisse.obtainResult(data)
                var index = 0
                val files = arrayOfNulls<File>(path.size)
                while (path.size > index) {
                    files[index] = File(path[index])
                    ++index
                }
                compress(uris)
                /*val fd = context.contentResolver.openFileDescriptor(uris[0], "r")
                val fis = FileInputStream(fd!!.fileDescriptor)
                val bytes = ByteArray(fis.available())
                if (fis.read(bytes) <= 0) {
                    return
                }
                val bais = ByteArrayInputStream(bytes)
//                val b = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                val b = BitmapFactory.decodeStream(fis)
                binding.imageView.setImageBitmap(b)
                Luban.with(this).load(object :InputStreamProvider{
                    override fun open(): InputStream {
                        return bais
                    }

                    override fun getPath(): String {
                        return path[0]
                    }

                }).ignoreBy(100).setCompressListener(object :OnCompressListener{
                    override fun onStart() {
                        showLoadingPop("压缩图片")
                    }

                    override fun onSuccess(file: File?) {
                        dismissLoadingPop()
                        if (file == null) {
                            return
                        }
                        imageUri = FileUtil.getUriForFile(context, file)
                        imagePath = file.absolutePath
                        LogUtils.i("Luban success, result path: " + file.absolutePath)
//                        val uri = FileUtil.getUriForFile(context, file)
//                        try {
//                            val fd = context.contentResolver.openFileDescriptor(uri, "r")
//                            val fis = FileInputStream(fd!!.fileDescriptor)
//                            val bytes = ByteArray(fis.available())
//                            if (fis.read(bytes) <= 0) {
//                                return
//                            }
//                            val b = BitmapFactory.decodeFileDescriptor(fd!!.fileDescriptor)
//                            binding.imageView.setImageBitmap(b)
//                        } catch (e: IOException) {
//                            e.printStackTrace()
//
//                            return
//                        }
                    }

                    override fun onError(e: Throwable?) {
                        dismissLoadingPop()
                        LogUtils.i("Luban error: "+e?.message)
                    }

                }).launch()**/
            }
        }
    }

    private fun compress(uris: List<Uri>) {
        ImageCompressor.with(context)
            .source(uris)
            .targetDir(AppConfig.imagePath)
            .maxSize(500)
            .maxWidthHeight(1080, 1920, true)
            .outputFormat(Bitmap.CompressFormat.JPEG)
            .compressCallback(
                object : CompressCallback {
                    override fun onStart() {
                        showLoadingPop("正在压缩图片")
                    }

                    override fun onSuccess(vararg file: File?) {
                        dismissLoadingPop()
                        imageUri = FileUtil.getUriForFile(context, file[0]!!)
                        imagePath = file[0]?.absolutePath
                        GlideUtils.load(
                            context,
                            imagePath,
                            binding.imageView,
                            0,
                            true,
                            R.mipmap.ic_launcher_round
                        )
                    }

                    override fun onError(throwable: Throwable?) {
                        dismissLoadingPop()
                        LogUtils.e(throwable?.message)
                    }

                }).launch()
    }

}